from django.shortcuts import render, redirect
from django.views.generic import TemplateView, View
from django.http import HttpResponse, JsonResponse, HttpResponseRedirect
from django.contrib.auth import login, logout, authenticate
from django.urls import reverse
from django.contrib.auth.mixins import LoginRequiredMixin
from users.models import Profile
from django.contrib.auth.models import User
from django.shortcuts import render_to_response,HttpResponse


	


# 登录用户
# 登录用户
class UserLoginView(TemplateView):
	template_name = 'login.html'

	def post(self, request):
		ret = {'status': 0}
		username = request.POST.get('username')
		password = request.POST.get('password')
		if username != 'admin':
			# session 中注入权限值
			PermAllow = {}
			pro = Profile.objects.all()
			for pr in pro:
				PermAllow[pr.user.username] = pr.user.is_superuser

			if username in PermAllow:
				#request.session['role_id'] = PermAllow[username]
				#request.session.set_expiry(3600)
				pass
			else:
				ret['status'] = 1
				ret['msg'] = '账号错误，请重新输入'
				return JsonResponse(ret)

		request.session['username'] = username
		request.session.set_expiry(3600)

		user = authenticate(username=username, password=password)
		if user:
			login(request, user)

		# ret['next_url'] = request.GET.get('next') if request.GET.get('next', None) else '/'
		# return HttpResponseRedirect('/dashboard/')

		else:
			ret['status'] = 1
			ret['msg'] = '密码错误,请重新输入'

		return JsonResponse(ret)

class ClearJson(LoginRequiredMixin, TemplateView):
	template_name = 'index.html'

	def get(self, request):
		jsdata = {
		  "code": 1,
		  "msg": "服务端清理缓存成功"
		}
		return JsonResponse(jsdata)


# 注销用户
class UserLogoutView(LoginRequiredMixin, View):

	def get(self, request):
		logout(request)
		request.session.flush()
		return HttpResponseRedirect(reverse('user_login'))